<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="75px">
<!--      <el-form-item label="所属课程" prop="platformId" v-if="!platformId">
        <el-select v-model="queryParams.platformId" placeholder="请选择课程" clearable>
          <el-option v-for="item in platformList" :key="item.baseId" :label="item.title" :value="item.baseId">
            <span style="float: left">{{ item.title }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              <dict-tag :options="dict.type.bmzt" :value="item.applyStatus" />
            </span>
          </el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item label="试卷标题" prop="paperName">
        <el-input v-model="queryParams.paperName" placeholder="请输入试卷标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="试卷类型" prop="type" v-if="!activeName">
        <el-select v-model="queryParams.type" placeholder="请选择试卷类型" clearable>
          <el-option v-for="dict in dict.type.sjlx" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:paperInfo:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['business:paperInfo:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:paperInfo:remove']">删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paperInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="baseId" v-if="false" />
      <el-table-column label="所属课程" align="center" prop="platformTitle" :show-overflow-tooltip="true" />
      <el-table-column label="试卷标题" align="center" prop="paperName" :show-overflow-tooltip="true" />
      <el-table-column label="总分数(分)" align="center" prop="totalScore" />
      <el-table-column label="合格分数(分)" align="center" prop="passingScore" />
      <el-table-column label="考试时长(分钟)" align="center" prop="duration" />
      <el-table-column label="考试模式" align="center" prop="modeType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sjms" :value="scope.row.modeType" />
        </template>
      </el-table-column>
      <el-table-column label="选项顺序" align="center" prop="modeSubject">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tgxxms" :value="scope.row.modeSubject" />
        </template>
      </el-table-column>
      <el-table-column label="是否生效" align="center" prop="change">
        <template slot-scope="scope">
          <el-switch @change="setMain(scope.row)" v-model="scope.row.isMain">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="出题数量(道题)" align="center" prop="subjectNum" />
      <el-table-column label="操作" width="250px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleReview(scope.row)">试卷预览</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleOption(scope.row)">题干管理</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:paperInfo:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:paperInfo:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-upload2" @click="handleImport(scope.row)">导入试题
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-download" @click="handleExport(scope.row)">导出试题
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="title" :visible.sync="openPreview" width="1000px" append-to-body>
      <Preview ref="preview" ></Preview>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openPreview=false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改试卷管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属课程" prop="platformId" v-if="!platformId">
          <el-select v-model="form.platformId" placeholder="请选择课程" clearable>
            <el-option v-for="item in platformList" :key="item.baseId" :label="item.title" :value="item.baseId">
              <span style="float: left">{{ item.title }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                <dict-tag :options="dict.type.bmzt" :value="item.applyStatus" />
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试卷标题" prop="paperName">
          <el-input v-model="form.paperName" placeholder="请输入试卷标题" />
        </el-form-item>
        <el-form-item label="试卷类型" prop="type" v-if="!type">
          <el-radio-group v-model="form.type">
            <el-radio v-for="dict in dict.type.sjlx" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="总分数" prop="totalScore">
          <el-input v-model="form.totalScore" @input="(v)=>(form.totalScore=v.replace(/[^\d.]/g,''))"
            placeholder="请输入总分数">
            <template slot="append">分</template>
          </el-input>
        </el-form-item>
        <el-form-item label="合格分数" prop="passingScore">
          <el-input v-model="form.passingScore" @input="(v)=>(form.passingScore=v.replace(/[^\d.]/g,''))"
            placeholder="请输入合格分数">
            <template slot="append">分</template>
          </el-input>
        </el-form-item>
        <el-form-item label="考试时长" prop="duration">
          <el-input v-model="form.duration" @input="(v)=>(form.duration=v.replace(/[^\d.]/g,''))" placeholder="请输入考试时长">
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
        <el-form-item label="考试模式" prop="modeType">
          <el-radio-group v-model="form.modeType" @change="radioChange">
            <el-radio v-for="dict in dict.type.sjms" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.modeType==1" label="出题数量" prop="subjectNum"
          :rules='[{required: true, message: "随机题干数量不能为空",trigger: "blur"}]'>
          <el-input v-model="form.subjectNum" @input="(v)=>(form.subjectNum=v.replace(/[^\d.]/g,''))"
            placeholder="请输入出题数量">
            <template slot="append">道题</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="form.modeType==2" label="自定义选题"
          :rules='[{required: true, message: "自定义选题数量不能为空，请在题干管理中维护题目。",trigger: "change"}]'>
          <!--<el-button :loading="buttonLoading" type="mini" @click="submitForm">新增</el-button>-->
          <el-transfer v-model="form.customs" :data="data" :titles="['题库', '被选题干']" @change="transfer"></el-transfer>
        </el-form-item>

        <el-form-item label="选项顺序" prop="modeSubject">
          <el-radio-group v-model="form.modeSubject">
            <el-radio v-for="dict in dict.type.tgxxms" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否生效" prop="isMain">
          <el-switch v-model="form.isMain">
          </el-switch>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-drawer :title="'试卷标题：' + formDetail.paperName" :visible.sync="dialog" direction="rtl" :append-to-body="true"
      size="60%">
      <PaperSubject ref="paperSubject" :paperId="formDetail.baseId"></PaperSubject>

    </el-drawer>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?paperId=' + upload.paperId" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    setMain,
    listPaperInfo,
    getPaperInfo,
    delPaperInfo,
    addPaperInfo,
    updatePaperInfo
  } from "@/api/business/paperInfo";
  import {
    platformList
  } from "@/api/business/platform";
  import PaperSubject from "../paperSubject/index.vue";
  import Preview from "./preview.vue";
  import {
    getToken
  } from "@/utils/auth";
  import {
    listPaperSubjects
  } from "@/api/business/paperSubject";

  export default {
    name: "PaperInfo",
    dicts: ['sjms', 'tgxxms', 'bmzt', 'sjlx'],
    components: {
      PaperSubject,
      Preview
    },
    props: {
      platformId: {
        type: String,
        default: ""
      },
      activeName: {
        type: String,
        default: ""
      },
      type: {
        type: String,
        default: ""
      }
    },
    /*watch: {
      activeName: {
        handler: function(val, oldVal) {
          this.queryParams.platformId = this.platformId;
          if (val === 'fourth' || val === 'fifty') {
            this.getList();
          }
        },
        immediate: true
      }
    },*/
    data() {
      return {
        data: [],
        openPreview: false,
        // 是否显示弹出层
        dialog: false,
        // 课程列表
        platformList: [],
        // 导入参数
        upload: {
          // 是否显示弹出层
          open: false,
          // 弹出层标题
          title: "",
          // 是否禁用上传
          isUploading: false,
          paperId: "",
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/business/paperSubject/import"
        },
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        id: '',
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 试卷管理表格数据
        paperInfoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          paperName: undefined,
          type: this.type,
          platformId: this.platformId
        },
        // 表单参数
        form: {},
        formDetail: {},
        // 表单校验
        rules: {
          type: [{
            required: true,
            message: "试卷类型不能为空",
            trigger: "change"
          }],
          platformId: [{
            required: true,
            message: "课程不能为空",
            trigger: "blur"
          }],
          paperName: [{
            required: true,
            message: "试卷标题不能为空",
            trigger: "blur"
          }],
          totalScore: [{
            required: true,
            message: "总分数不能为空",
            trigger: "blur"
          }],
          passingScore: [{
            required: true,
            message: "合格分数不能为空",
            trigger: "blur"
          }],
          duration: [{
            required: true,
            message: "考试时长不能为空",
            trigger: "blur"
          }],
          isMain: [{
            required: true,
            message: "是否生效不能为空",
            trigger: "change"
          }],
          modeType: [{
            required: true,
            message: "试卷模式不能为空",
            trigger: "change"
          }],
          modeSubject: [{
            required: true,
            message: "题干选项模式不能为空",
            trigger: "change"
          }],

        }
      };
    },
    created() {
      this.getList();
      this.getPlatformList();
    },
    methods: {
      /** 导入按钮操作 */
      handleImport(row) {
        this.upload.paperId = row.baseId
        this.upload.title = "导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        window.open("试题导入模板.xlsx", '_blank')
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response
          .msg + "</div>", "导入结果", {
            dangerouslyUseHTMLString: true
          });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      transfer() {
        this.$forceUpdate();
      },
      radioChange() {
        if (this.form.modeType == 2) {
          listPaperSubjects({
            paperId: this.id
          }).then(response => {
            this.data = [];
            response.data.forEach(item => {
              this.data.push({
                key: item.baseId.toString(),
                label: `(${item.subjectScore}分)${item.subjectName}`,
              })
            })
          });
        }
      },
      getPlatformList() {
        platformList().then(response => {
          this.platformList = response.data;
        });
      },
      setMain(row) {
        let params = {
          "baseId": row.baseId,
          "isMain": row.isMain
        }
        setMain(params).then(() => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
        }).finally(() => {
          this.getList();
        });
      },
      /** 查询试卷管理列表 */
      getList() {
        this.loading = true;
        listPaperInfo(this.queryParams).then(response => {
          this.paperInfoList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      //试卷预览
      handleReview(row) {
        this.title = "试卷预览";
        this.openPreview = true;
        this.$nextTick(() => {
          this.$refs.preview.genPaper(row.baseId);
        });
        /*this.$router.push({
               name: "Preview",
               query: {
                 id: row.baseId,
                 type: 1
               }
             });*/
      },
      handleOption(row) {
        this.dialog = true;
        this.formDetail = row;
        this.$refs.paperSubject.getList();
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          baseId: undefined,
          platformId: this.platformId,
          paperName: undefined,
          type: this.type,
          totalScore: undefined,
          passingScore: undefined,
          duration: undefined,
          isMain: false,
          modeType: 0,
          modeSubject: 1,
          customSubject: undefined,
          customs: [],
          subjectNum: undefined,
          delFlag: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.baseId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加试卷管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        const baseId = row.baseId || this.ids
        this.id = baseId;
        getPaperInfo(baseId).then(response => {
          this.loading = false;
          this.form = response.data;
          if (this.form.customSubject) {
            this.form.customs = this.form.customSubject.split(",");
          } else {
            this.form.customs = [];
          }
          this.open = true;
          this.title = "修改试卷管理";
          this.radioChange();
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.form.customs) {
              this.form.customSubject = this.form.customs.join(",");
            }
            if (this.form.baseId != null) {
              updatePaperInfo(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addPaperInfo(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const baseIds = row.baseId || this.ids;
        this.$modal.confirm('是否确认删除试卷管理编号为"' + baseIds + '"的数据项？').then(() => {
          this.loading = true;
          return delPaperInfo(baseIds);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {}).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport(row) {
        this.download('business/paperSubject/export?paperId=' + row.baseId, {
          ...this.queryParams
        }, `paperInfo_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
